package com.chapter.sample.config.mysql;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot3.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
// 扫描主数据源的 Mapper 包
@MapperScan(basePackages = "com.chapter.sample.dao.member", sqlSessionFactoryRef = "primarySqlSessionFactory")
public class PrimaryDataSourceConfig {

    @Bean(name = "primaryDataSource", initMethod = "init")
    @ConfigurationProperties(prefix = "spring.datasource.druid.primary")
    public DruidDataSource primaryDataSource() {
        //return DataSourceBuilder.create().build();
        DruidDataSource dataSource = DruidDataSourceBuilder.create().build();
        System.out.println("Primary DataSource URL: " + ((DruidDataSource) dataSource).getUrl());
        return dataSource;
        //return new DruidDataSource();
    }
    @Primary
    @Bean(name = "primarySqlSessionFactory")
    public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception {
        System.out.println("2 Primary DataSource URL: " + ((DruidDataSource) dataSource).getUrl());

        MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:/mybatis/member/*.xml"));
        return sessionFactory.getObject();
    }

    @Primary
    @Bean(name = "primaryTransactionManager")
    public DataSourceTransactionManager primaryTransactionManager(@Qualifier("primaryDataSource") DataSource dataSource) {
        System.out.println("3 Primary DataSource URL: " + ((DruidDataSource) dataSource).getUrl());

        return new DataSourceTransactionManager(dataSource);
    }

    @Primary
    @Bean(name = "primarySqlSessionTemplate")
    public SqlSessionTemplate primarySqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }




    /**
     * MyBatis-Plus自动填充功能
     */
//    static class MetaObjectHandlerImplMaster implements MetaObjectHandler {
//
//        @Autowired
//        private TokenService tokenService;
//
//        @Override
//        public void insertFill(MetaObject metaObject) {
//            Date now = new Date();
//            this.setFieldValByName("createTime", now, metaObject);
//            this.setFieldValByName("updateTime", now, metaObject);
//            this.setFieldValByName("delFlag", 0, metaObject);
//            User user = tokenService.getUserInfo();
//            if (null != user) {
//                this.setFieldValByName("createId", user.getId(), metaObject);
//                this.setFieldValByName("createName", user.getName(), metaObject);
//                this.setFieldValByName("updateId", user.getId(), metaObject);
//                this.setFieldValByName("updateName", user.getName(), metaObject);
//            }
//
//        }
//
//        @Override
//        public void updateFill(MetaObject metaObject) {
//            this.setFieldValByName("updateTime", new Date(), metaObject);
//            User user = tokenService.getUserInfo();
//            if (null != user) {
//                this.setFieldValByName("updateId", user.getId(), metaObject);
//                this.setFieldValByName("updateName", user.getName(), metaObject);
//            }
//        }
//    }

    /**
     * MyBatis-Plus拦截器
     */
//    @Bean
//    public MybatisPlusInterceptor mybatisPlusInterceptorMaster() {
//        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//        //添加分页拦截器
//        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
//        //添加乐观锁拦截器
//        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
//        return interceptor;
//    }


    /**
     * 读取MyBatis-Plus配置
     */
//    @Bean
//    @ConfigurationProperties(prefix = "mybatis-plus.global-config")
//    public GlobalConfig globalConfigMaster() {
//        GlobalConfig globalConfig = new GlobalConfig();
//        //添加自动填充配置
//        //globalConfig.setMetaObjectHandler(new MetaObjectHandlerImplMaster());
//        return globalConfig;
//    }

    /**
     * 读取MyBatis-Plus配置文件
     */
//    @Bean
//    @ConfigurationProperties(prefix = "mybatis-plus.configuration")
//    public MybatisConfiguration mybatisConfigurationMaster() {
//        return new MybatisConfiguration();
//    }
}
